package com.twu.biblioteca;

import java.util.*;

/**
 * Created by kathy on 12/04/14.
 * This class is to demonstrate returning book
 */
public class ReturnBookAction implements Action{

    private Library library;
    private IUserLogin userLogin;
    private IConsoleWriter consoleWriter;
    private IConsoleReader consoleReader;

    public ReturnBookAction(Library library, IConsoleReader consoleReader,
                            IConsoleWriter consoleWriter, IUserLogin userLogin){

        this.library = library;

        // those attributes are used for mock test.
        this.userLogin = userLogin;
        this.consoleWriter = consoleWriter;
        this.consoleReader = consoleReader;
    }

    public void execute(){

        if(BibliotecaApp.currentUser != null) {
            consoleWriter.println("Please input the book id for return: ");
            String id = consoleReader.readInput().toLowerCase().trim();

            while (!returnBook(id) && !id.equals("menu")) {
                consoleWriter.println("That is not a valid book to return. Please re-input or press 'menu' to back to main menu ");
                id = consoleReader.readInput();
            }
            if (!id.equals("menu"))
                consoleWriter.println("Thank you for returning the book");
        }
    }

    // This method is to let customer return a book,
    // then returns true if it is successful
    public boolean returnBook(String bookId){

        bookId = bookId.toLowerCase();

        for(Book aBook : library.getBookRepository()){
            if(aBook.getId().toString().toLowerCase().equals(bookId)){
                aBook.setUser(null); // book is available after returned
                return true;
            }
        }
        return false;
    }
}
